package ai.fabu.dataplatform.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class UrlResource {

    //获取网络文件，转存到fileDes中，fileDes需要带文件后缀名
    public static void saveUrlFile(String fileUrl, String fileDes) throws Exception {
        log.info("saveUrlFile: file path: {}", fileDes);
        File toFile = new File(fileDes);
        if(!FileUtil.createFileRecursively(toFile)){
            log.error("saveUrlFile: create file: {} fail", toFile.getAbsolutePath());
        }
        FileOutputStream outImgStream = new FileOutputStream(toFile);
//        byte[] urlFileData = getUrlFileData(fileUrl);
        outImgStream.write(getUrlFileData(fileUrl));

        outImgStream.close();
    }

    //获取链接地址文件的byte数据 //直接获取的就是二进制数据孟德佳
    public static byte[] getUrlFileData(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.connect();
        InputStream cin = httpConn.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = cin.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        cin.close();
        byte[] fileData = outStream.toByteArray();
        outStream.close();
        return fileData;
    }
//
//    //获取链接地址的字符数据，wichSep是否换行标记
//    public static String getUrlDetail(String urlStr, boolean withSep) throws Exception {
//        URL url = new URL(urlStr);
//        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//        httpConn.connect();
//        InputStream cin = httpConn.getInputStream();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(cin, "UTF-8"));
//        StringBuffer sb = new StringBuffer();
//        String rl = null;
//        while ((rl = reader.readLine()) != null) {
//            if (withSep) {
//                sb.append(rl).append(System.getProperty("line.separator"));
//            } else {
//                sb.append(rl);
//            }
//        }
//        return sb.toString();
//    }

}